﻿using Azure.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebServer.InternalService;

namespace WebServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController(UserService userService, IConfiguration config) : ControllerBase
    {
        [HttpGet]
        public IActionResult Auth(string username, string password)
        {
            if (userService.VerifyLogin(username, password))
            {
                var token = GenerateJwtToken(username, userService.GetUserRole(username));

                return Ok(new { token, message = "", success = true, datetime = DateTime.Now });
            }
            return Ok(new { message = "获取用户信息失败，请检查输入的用户名和密码是否正确！", success = false, datetime = DateTime.Now });
        }


        private string GenerateJwtToken(string username, List<string> roles)
        {
            var claims = new List<Claim> { new(ClaimTypes.Name, username) };
            claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

            var key = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(config["Jwt:SecretKey"])
            );
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: config["Jwt:Issuer"],
                audience: config["Jwt:Audience"],
                claims: claims,
                expires: DateTime.Now.AddDays(7),
                signingCredentials: creds
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        [Authorize]
        [HttpGet]
        [Route("user-info")]
        public IActionResult GetUserInfo()
        {
            var user = HttpContext.User;
            if (user.Identity.IsAuthenticated)
            {
                var username = user.Identity.Name;
                var roles = user.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToList();
                return Ok(new { username, roles });
            }
            return Unauthorized();
        }
    }
}